import { NextResponse } from 'next/server';
import { getDb } from '@/lib/json-database';

export async function GET(
  request: Request,
  { params }: { params: Promise<{ specialtyName: string }> }
) {
  try {
    const db = getDb();
    const allDevices = db.getAllDevices();
    const resolvedParams = await params;
    const specialtyName = resolvedParams.specialtyName;

    const specialtyDevices = allDevices.filter(device => {
      // Create a mapping from frontend route name to backend specialty name in CSV
      const specialtyMap: { [key: string]: string } = {
        'piping': '配管专业',
        'electrical': '电气专业',
        'hvac': '暖通专业',
        'communication': '通信专业',
        'instrumentation': '仪表专业'
      };
      return device.specialty === specialtyMap[specialtyName];
    });

    if (!specialtyDevices || specialtyDevices.length === 0) {
      return NextResponse.json({ error: 'No devices found for this specialty' }, { status: 404 });
    }

    return NextResponse.json({ success: true, devices: specialtyDevices });

  } catch (error) {
    const message = error instanceof Error ? error.message : 'An unknown error occurred';
    console.error(`Failed to get data for specialty: ${message}`);
    return NextResponse.json({ success: false, error: 'Failed to retrieve specialty data.' }, { status: 500 });
  }
} 